/** @format */

import { isBoolean, isNumber, isObject, isString, isUndefined } from 'lodash'
import { get } from 'mpath'
import { CODE_TYPES } from '../../../errorCode'
import { resultsModel } from '../../../sdk'

export interface IGameLimitCondition {
  $eq?: any
  $gt?: any
  $gte?: any
  $in?: any[]
  $lt?: any
  $lte?: any
  $ne?: any
}

export interface IGameLimit {
  [params: string]: string | boolean | number | IGameLimitCondition
}

export default function checkUserInfo(gameLimit: IGameLimit, error: ICodeType | string) {
  return async (context: IContext<{ activityId: string }>, { userInfo }: IControllerInfos) => {
    const allValid = validateData(userInfo, gameLimit)

    if (!allValid)
      return resultsModel.error(isObject(error) ? error : CODE_TYPES.SYSTEM_ERROR, isString(error) ? error : '')

    console.log(allValid)
    // const { id } = context.data
  }
}

export function checkGameTimes(count: number) {
  return checkUserInfo({ gameTimes: { $gte: count } }, '游戏次数不足')
}

function validateData(data: any = {}, condition: IGameLimit) {
  let allValid = true
  Object.keys(condition).forEach(key => {
    const value = condition?.[key]
    if (isString(value) || isBoolean(value) || isNumber(value)) {
      allValid = validateEq(data, key, value)
    }
    if (isObject(value)) {
      !isUndefined(value?.$eq) && (allValid = validateEq(data, key, value?.$eq))
      !isUndefined(value?.$gt) && (allValid = validateGt(data, key, value?.$gt))
      !isUndefined(value?.$gte) && (allValid = validateGte(data, key, value?.$gte))
      !isUndefined(value?.$lte) && (allValid = validateLte(data, key, value?.$lte))
      !isUndefined(value?.$lt) && (allValid = validateLt(data, key, value?.$lt))
      !isUndefined(value?.$in) && (allValid = validateIn(data, key, value?.$in))
      !isUndefined(value?.$ne) && (allValid = validateNe(data, key, value?.$ne))
    }
  })
  return allValid
}

function validateEq(data: any = {}, key: string, value: any) {
  return get(key, data) === value
}

function validateGt(data: any = {}, key: string, value: any) {
  return get(key, data) > value
}
function validateGte(data: any = {}, key: string, value: any) {
  return get(key, data) >= value
}

function validateLt(data: any = {}, key: string, value: any) {
  return get(key, data) < value
}

function validateLte(data: any = {}, key: string, value: any) {
  return get(key, data) <= value
}

function validateIn(data: any = {}, key: string, value: any[]) {
  return value.includes(get(key, data))
}

function validateNe(data: any = {}, key: string, value: any) {
  return get(key, data) !== value
}
